package Java7_Concurrency_Cookbook.thread_synchronized_helper.phaser;

import java.util.concurrent.Phaser;

/**
 * Phaser 对象用于在每个阶段结束时对线程同步进行控制.
 * Phaser 对象构造传入了参与阶段同步的线程个数.
 *
 * 本示例启动了三个搜索线程, 每个线程完成相应的阶段(如启动, checkResults, showInfo)后,
 * 会调用 arriveAndAwaitAdvance 或 arriveAndDeregister 来等待其它线程到达这个阶段, 并一起进入下一个阶段.
 * 参与 phaser 的线程可以有多个阶段.
 * @author lixiangke
 * @date 2017/11/14
 */
public class Main {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(3);
        FileSearch system = new FileSearch("C:\\Windows", "log", phaser);
        FileSearch apps = new FileSearch("C:\\Program Files", "log", phaser);
        FileSearch documents = new FileSearch("C:\\Users\\xiangke\\Documents", "log", phaser);

        Thread systemThread = new Thread(system, "System");
        systemThread.start();
        Thread appsThread = new Thread(apps, "Apps");
        appsThread.start();
        Thread documentsThread = new Thread(documents, "Documents");
        documentsThread.start();

        try {
            systemThread.join();
            appsThread.join();
            documentsThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Terminated: " + phaser.isTerminated());
    }
}
